import pymysql
from flask import Blueprint, render_template, request, jsonify

from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.models import MoniEquipListModels
from applications.schemas import MoniEquipListOutSchema
from applications.extensions import db
import random,datetime
from applications.common import curd
from applications.common.utils.rights import authorize
from applications.models import TrainData2, ReportListModels
from applications.common.utils.http import table_api, fail_api, success_api
import pymysql
from dotenv import dotenv_values

config = dotenv_values('.flaskenv')
# MySql配置信息
HOST = config.get('MYSQL_HOST') or '43.143.212.210'
PORT = config.get('MYSQL_PORT') or 3306
DATABASE = config.get('MYSQL_DATABASE') or 'pearadminflask'
USERNAME = config.get('MYSQL_USERNAME') or 'root'
PASSWORD = config.get('MYSQL_PASSWORD') or 'MxD23680'

emerg_select_bp = Blueprint('EmergySelect', __name__, url_prefix='/admin/screen/training')


# 突发事件模拟进入接口
@emerg_select_bp.get('/')
@authorize("admin:screen:training", log=True)
def main():
    Blood_oxygen = round(random.uniform(96, 98), 2)
    blood_pressure = random.randint(110, 115)
    Respiratory_rate = random.randint(18, 26)
    heart_rate = random.randint(65, 80)
    temperature = round(random.uniform(36.2, 36.7), 2)
    # user_name = train.user_name,
    # scene_name = train.scene_name,
    # train_name = train.train_name,
    # start_time = train.start_time

    # 数据库数据插入
    # db = pymysql.connect(host=HOST, port=int(PORT), user=USERNAME, password=PASSWORD, charset='utf8mb4')
    # c1 = db.cursor()
    # sql = "INSERT INTO user(username, password) VALUES ('%s','%s')" % (username, password)
    # # 获取异常
    # try:
    #     c1.execute(sql)
    #     # 提交数据
    #     db.commit()
    #     return jsonify(status=200, msg='插入成功')
    #
    # # 异常错误
    # except:
    #     db.rollback()
    #     print("注册失败")
    #     return jsonify(status=400, msg='插入失败')
    #
    # # 关闭
    # db.close()
    report_detail = curd.get_one_by_id(ReportListModels, 1)
    return render_template('admin/emerge_firedill_detail.html',
                           report_detail=report_detail,
                           Blood_oxygen=Blood_oxygen,
                           blood_pressure=blood_pressure,
                           Respiratory_rate=Respiratory_rate,
                           heart_rate=heart_rate,
                           temperature=temperature,
                           )


# 火灾模拟进入接口 与qt联通
@emerg_select_bp.get('/emerge_firedill_data')
def ermerg_fire_training():

    police_id = request.args.get('user_id', type=int)
    user_name = xss_escape(request.args.get('user_name', type=str))
    time_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    evacuat_num = request.args.get('evacuat_num', type=int)
    fire_size = request.args.get('fire_size', type=int)
    fire_range = request.args.get('fire_range', type=int)
    build_exist = xss_escape(request.args.get('build_exist', type=str))
    temp_control = request.args.get('temp_control', type=int)
    decision_maker_num = request.args.get('decision_maker_num', type=int)
    scheme_num = request.args.get('scheme_num', type=int)
    recognition_ratio = request.args.get('recognition_ratio', type=int)
    wind_size = request.args.get('wind_size', type=int)

    police_id = police_id if not police_id == None else 0
    user_name = user_name if not user_name == None else "暂无"
    evacuat_num = evacuat_num if not evacuat_num == None else 0
    fire_size = fire_size if not fire_size ==  None else 0
    fire_range = fire_range if not fire_range == None else 0
    build_exist = build_exist if not len(build_exist) == None else "无"
    temp_control = temp_control if not temp_control == None else 0
    decision_maker_num = decision_maker_num if not decision_maker_num == None else 0
    scheme_num = scheme_num if not scheme_num == None else 0
    recognition_ratio = recognition_ratio if not recognition_ratio == None else 0
    wind_size = wind_size if not wind_size == None else 0

    record = ReportListModels(police_id=police_id,tranning_state = 2, tranning_name='火灾模拟训练', \
                        name=user_name, create_time=time_now,fireDegree=fire_size,fireRange= fire_range, \
                              evacuat_num = evacuat_num,windSpeed= wind_size,haveBuild= build_exist,tempControl=temp_control, \
                              decision_maker_num= decision_maker_num, scheme_num = scheme_num,recognition_ratio=recognition_ratio)
    db.session.add(record)
    # c1 = db.cursor()
    try:
        # c1.execute(record)
        # 提交数据
        db.session.commit()

    # 异常错误
    except:
        print("插入失败")

    report_detail = record
    Blood_oxygen = round(random.uniform(96, 98), 2)
    blood_pressure = random.randint(110, 115)
    Respiratory_rate = random.randint(18, 26)
    heart_rate = random.randint(65, 80)
    temperature = round(random.uniform(36.2, 36.7), 2)
    return render_template('admin/emerge_firedill_detail.html',
                           report_detail=report_detail,
                           Blood_oxygen=Blood_oxygen,
                           blood_pressure=blood_pressure,
                           Respiratory_rate=Respiratory_rate,
                           heart_rate=heart_rate,
                           temperature=temperature,
                           )


# @emerg_select_bp.put('/update_database')
# def update():
#     req_json = request.json
#     return "PPP"


# 火灾模拟详情
# @emerg_select_bp.get('/report_detail/<int:id>')
# # @authorize("xxxxxxxxxxxxxxxxxxx", log=True)
# def equip_list_details(id):
#     global report_detail
#
#     report_detail = curd.get_one_by_id(ReportListModels, id)
#     return render_template('admin/emergy_report_detail.html', report_detail=report_detail)
@emerg_select_bp.post('/report_detail_updateData')
def equip_list_details_upadateData():

    id = request.json.get("id")
    evacuat_num = request.json.get("evacuat_num")
    decision_maker_num = request.json.get("decision_maker_num")
    scheme_num = request.json.get("scheme_num")
    recognition_ratio = request.json.get("recognition_ratio")
    fire_size = request.json.get("fire_size")
    wind_size = request.json.get("wind_size")
    temp_control = request.json.get("temp_control")
    fire_range = request.json.get("fire_range")
    build_exist = request.json.get("build_exist")

    report = ReportListModels.query.get(id)
    fire_size1 = fire_size if not fire_size == 0 else report.fireDegree
    fire_range1 = fire_range if not fire_range == 0 else report.fireRange
    evacuat_num1 = evacuat_num if not evacuat_num == None else report.evacuat_num
    decision_maker_num1 = decision_maker_num if not decision_maker_num == None else report.decision_maker_num
    scheme_num1 = scheme_num if not scheme_num == None else report.scheme_num
    recognition_ratio1 = recognition_ratio if not recognition_ratio == None else report.recognition_ratio
    wind_size1 = wind_size if not wind_size == 0 else report.windSpeed
    temp_control1 = temp_control if not temp_control == 0 else report.tempControl
    build_exist1 = build_exist if not len(build_exist) > 0 else report.haveBuild
    ReportListModels.query.filter_by(id=id).update({'fireDegree': fire_size1, 'fireRange': fire_range1, 'evacuat_num': evacuat_num1,\
                                                    'decision_maker_num':decision_maker_num1,'decision_maker_num':decision_maker_num1,\
                                                    'scheme_num':scheme_num1,'recognition_ratio':recognition_ratio1,\
                                                     'windSpeed':wind_size1,'tempControl':temp_control1,'haveBuild':build_exist1})
    db.session.commit()
    return success_api(msg="更新成功")

